/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2009 - 2012 Luca Mingardi.
 *
 * This file is part of jeeObserver.
 *
 * JeeObserver is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * JeeObserver is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */
package jeeobserver.logger;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * The Class LoggerFormatter.
 *
 * @author Luca Mingardi
 * @version 4.0
 */
public final class LoggerFormatter extends Formatter {

	@Override
	public String format(LogRecord record) {

		final StringBuilder stringBuilder = new StringBuilder();

		final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		final Date date = new Date(record.getMillis());

		// Logger name
		stringBuilder.append("[").append(record.getLoggerName()).append("]");
		stringBuilder.append(" ");

		// Date
		stringBuilder.append(dateFormat.format(date));
		// stringBuffer.append(date.toString());

		stringBuilder.append(" ");

		// Level
		stringBuilder.append(record.getLevel().getName());
		stringBuilder.append(": ");

		// Message
		stringBuilder.append(this.formatMessage(record));
		stringBuilder.append("\n");

		if (record.getThrown() != null) {
			final StringWriter stringWriter = new StringWriter();
			final PrintWriter printWriter = new PrintWriter(stringWriter);
			record.getThrown().printStackTrace(printWriter);

			stringBuilder.append(stringWriter.toString());
		}

		return stringBuilder.toString();
	}
}
